import {
  NPCCEnum
} from '@/utils/ccplugin/NPCCEnum'
import {
  ErrorCode
} from '@/utils/ccplugin/NPCCErrorCode'
import {
  NPCCIF
} from '@/utils/ccplugin/NPCCInterface'
import {
  NPCCILY
} from '@/utils/ccplugin/NPCCInterlayer'
import {
  NPCCStruct
} from '@/utils/ccplugin/NPCCStruct'
import {
  NPCCUtils
} from '@/utils/ccplugin/NPCCUtils'
import {WebPreview} from './preview'
import {WebTree} from './tree'
import {
  getSubRes, getSubResCameraHandle, getSiblingRes, onlineDevice
} from './public'
export var WebClient = {
  _this:null,
  connectId: null,
  resource: new NPCCUtils.Hash(),
  puResList: null,
  hServer: null,
  rootDomainName: null,
  strDir: 'C:\\RST_Client\\',
  chatStatusHasLogin: false,
  // 初始化，加载插件
  Load: function (_this) {
    try {
      // 首先初始化NPCCILY，加载插件
      var operator = NPCCILY.Init(new NPCCStruct.InitParamStruct(false, null, null));
      WebClient._this = _this
      if (operator.errorCode != ErrorCode.NP_E_OK) {
        // 初始化不成功
        alert(ErrorCode.Error2Desc(operator.errorCode));
        return false;
      } else {
        var version = NPCCILY.Plug.ccPlugin.version; // 获取cc插件版本号 
        // 存储窗口容器信息
        console.log('存储窗口容器信息')
        console.log(_this.$refs.resourceTree)
        if (_this.$refs.resourceTree) {
          console.log('存放了')
          // 存放窗口容器信息，总共有12个窗口
          NPCCILY.windowContainers.set('video11', new NPCCStruct.WindowContainerStruct(_this.$refs.video11, false, null, null));
          NPCCILY.windowContainers.set('video12', new NPCCStruct.WindowContainerStruct(_this.$refs.video12, false, null, null));
          NPCCILY.windowContainers.set('video13', new NPCCStruct.WindowContainerStruct(_this.$refs.video13, false, null, null));
          NPCCILY.windowContainers.set('video14', new NPCCStruct.WindowContainerStruct(_this.$refs.video14, false, null, null));

          NPCCILY.windowContainers.set('video21', new NPCCStruct.WindowContainerStruct(_this.$refs.video21, false, null, null));
          NPCCILY.windowContainers.set('video22', new NPCCStruct.WindowContainerStruct(_this.$refs.video22, false, null, null));
          NPCCILY.windowContainers.set('video23', new NPCCStruct.WindowContainerStruct(_this.$refs.video23, false, null, null));
          NPCCILY.windowContainers.set('video24', new NPCCStruct.WindowContainerStruct(_this.$refs.video24, false, null, null));

          NPCCILY.windowContainers.set('video31', new NPCCStruct.WindowContainerStruct(_this.$refs.video31, false, null, null));
          NPCCILY.windowContainers.set('video32', new NPCCStruct.WindowContainerStruct(_this.$refs.video32, false, null, null));
          NPCCILY.windowContainers.set('video33', new NPCCStruct.WindowContainerStruct(_this.$refs.video33, false, null, null));
          NPCCILY.windowContainers.set('video34', new NPCCStruct.WindowContainerStruct(_this.$refs.video34, false, null, null));
        }
        // 存放窗口容器信息(实时回放)
        NPCCILY.windowContainers.set('videoPlayback', new NPCCStruct.WindowContainerStruct(_this.$refs.videoPlayback, false, null, null));
      }
      return true;
    } catch (e) {
      alert('Load exception: ' + e.name + '::' + e.message);
      return false;
    }
  },
   // 释放插件
   Free: function () {
     NPCCILY.Free();
   },
   // 创建窗口 3x4：总共12个视频播放窗口
   CreateVideoWindow: function (windowContainerStruct) {
     // for (var i=0;i<3;i++) {
     //     for (var j=0;j<4;j++) {
     //         var key = 'video' + ((i+1) * 10 + j + 1);
     //         var windowContainerStruct = NPCCILY.windowContainers.get(key);
     if (windowContainerStruct) {
       // 创建窗口
       var window = NPCCILY.CreateWindow(WebClient.connectId, windowContainerStruct.container);
       if (window.errorCode == ErrorCode.NP_E_OK) {
         windowContainerStruct.window = window.value;
         var windowEvent = new NPCCStruct.WindowEventStruct();
         // 左键单击事件
         windowEvent.lbtn_click.status = true;
         windowEvent.lbtn_click.callback = function (notify) {
           WebClient.ReceivePWEvent(notify);
         };
         NPCCILY.WindowAttachEvent.Init(windowContainerStruct.window, windowEvent);

         var windowEvent2 = new NPCCStruct.WindowEventStruct();
         // 全屏窗口显示
         windowEvent2.full_screen_window_show.status = true;
         windowEvent2.full_screen_window_show.callback = function (notify) {
           WebClient.ReceivePWEvent(notify);
         };
         NPCCILY.WindowAttachEvent.Init(windowContainerStruct.window, windowEvent2);

         var windowEvent3 = new NPCCStruct.WindowEventStruct();
         // 全屏窗口隐藏
         windowEvent3.full_screen_window_hide.status = true;
         windowEvent3.full_screen_window_hide.callback = function (notify) {
           WebClient.ReceivePWEvent(notify);
         };
         NPCCILY.WindowAttachEvent.Init(windowContainerStruct.window, windowEvent3);
       }
     }
     //     }
     // }
   },
    // 建立连接
    Login: function (data,callback) {
        // $('.previewLi').addClass('active').siblings().removeClass('active');
        // $('.preview').css('display', 'block').siblings().not('.opeNav').css('display', 'none');

        NPCCILY.CCNotifyManager.Add(
          NPCCEnum.CCObjectNotify.login_notify,
          function (loginStatus) {
            WebClient.ReceiveLoginCallback(loginStatus,data,function(res){
              callback(res)
            });
          }
        );

        var ipVal = data.ip;
        var portVal = data.port;
        var userNameVal = data.userName;
        var pwdVal = data.pwd;
        var root = 'root';

        // 调用建立登录函数
        var operator = NPCCIF.RSTW_LoginNoBlock(NPCCILY.Plug.ccPlugin, ipVal, portVal,
          NPCCUtils.encodeUnicode(NPCCUtils.UnicodetoUTF8(userNameVal)), pwdVal, root);
        if (operator.errorCode == ErrorCode.NP_E_OK) {
          // $('#login').html('退出');
          // $(".closeView").attr("disabled", false);
        } else {
          // $('#login').html('登录');
          WebClient.Logout();
          alert('登录失败: ' + ErrorCode.Error2Desc(operator.errorCode));
        }
      },

      // 回调函数
      ReceiveLoginCallback: function (loginStatus,data,callback) {
        if (loginStatus.errorCode == 0) {
          if (!WebClient.hServer) {
            WebClient.hServer = loginStatus.pServer;
          }

         var ipVal = data.ip;
         var portVal = data.port;
         var userNameVal = data.userName;
         var pwdVal = data.pwd;
         var root = 'root';

          switch (loginStatus.status) {
            case NPCCEnum.LoginStatus.LS_COMPLETED:
              var connectId = new Date().getTime() + "" + parseInt(Math.random() * (9999 - 1000 + 1) + 1000);
              var globalData = new NPCCStruct.InitGlobalDataStruct(WebClient.hServer,
                new NPCCStruct.LoginParamStruct(ipVal, portVal, root,
                  NPCCUtils.encodeUnicode(NPCCUtils.UnicodetoUTF8(userNameVal)), pwdVal));
              NPCCILY.serverMap.set(connectId, globalData);
              WebClient.connectId = connectId;
              setTimeout(function () {
                WebClient.getInfo(function(res){
                  callback(res)
                });
              }, 100)

              break;
            default:
              break;
          }
        } else {
          // 登录失败
          // $('#login').html('登录');
          WebClient.Logout();
        }
      },
      getInfo: function(callback) {
        var operator = NPCCIF.COMMON_GetName(NPCCILY.Plug.ccPlugin, WebClient.hServer);
        if (operator.errorCode == ErrorCode.NP_E_OK) {
            // 添加预览视频窗口句柄以及添加窗口事件
            // WebClient.CreateVideoWindow();
            // 添加CC插件事件回调
            WebClient.AddCCEvent();
            var rootDomainName = operator.value || '网络视频监控系统';
            WebClient.rootDomainName = rootDomainName;
            console.log('服务器名称：%s', rootDomainName);
            console.log('登录成功');
            var windowContainerStruct = NPCCILY.windowContainers.get('video11');
            console.log(windowContainerStruct)
            windowContainerStruct.focus = true;
            
            WebPreview.ClickVideoWindow(windowContainerStruct.window);
            // 实时指挥与平台构造资源数
            WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, WebClient._this.$refs.resourceTree, NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_platform,function(res){
              callback(res)
            });
            // 前端构造资源树
            // WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, WebClient._this.$refs.resourceTreeFrond, NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_frond);
            // $('.resourceTreeFrond').css('display', 'none');
            // var platformOrLocalSelectText = $("#platformOrLocalSel").find("option:selected").text();
            // var viewOrPhotoSelectText = $("#viewOrPhotoSel").find("option:selected").text();
            
            
            // 
            //录像
            //

            //本地录像树
            // WebQuery.localVideoDateInfo([], WebClient.strDir);

            //本地图片树
            // WebQuery.localPhotoDateInfo([], WebClient.strDir);
            // if (platformOrLocalSelectText == "平台") {
            //     if (viewOrPhotoSelectText == '录像') {
            //         $('#dateInfoPhotoTree').css('display', 'none');
            //         $('#dateInfoVideoTree').css('display', 'none');
            //         $('#dateInfoPlatTree').css('display', 'block');
            //         $('.dateInfoPhotoTb').css('display', 'none');
            //         $('.dateInfoVideoTb').css('display', 'block');
            //         $('#tb_1_tbody').html('');
            //     }
            //     else if (viewOrPhotoSelectText == '图片') {
            //         $('#dateInfoPhotoTree').css('display', 'none');
            //         $('#dateInfoVideoTree').css('display', 'none');
            //         $('#dateInfoPlatTree').css('display', 'block');
            //         $('.dateInfoVideoTb').css('display', 'none');
            //         $('.dateInfoPhotoTb').css('display', 'block');
            //         $('#tb_2_tbody').html('');
            //     }
            // }
            // else {
            //     if (viewOrPhotoSelectText == '录像') {
            //         $('#dateInfoPhotoTree').css('display', 'none');
            //         $('#dateInfoVideoTree').css('display', 'block');
            //         $('#dateInfoPlatTree').css('display', 'none');
            //         $('.dateInfoPhotoTb').css('display', 'none');
            //         $('.dateInfoVideoTb').css('display', 'block');
            //     }
            //     else if (viewOrPhotoSelectText == '图片') {
            //         $('#dateInfoPhotoTree').css('display', 'block');
            //         $('#dateInfoVideoTree').css('display', 'none');
            //         $('#dateInfoPlatTree').css('display', 'none');
            //         $('.dateInfoVideoTb').css('display', 'none');
            //         $('.dateInfoPhotoTb').css('display', 'block');
            //     }
            // }
        }
        else {
           alert('获取服务器名称失败: ' + ErrorCode.Error2Desc(operator.errorCode));
        }
    },

    // 退出平台
  Logout: function (logindata,callback) {
    var arr=[] //关闭视频数组
        try {
            var keys = NPCCILY.windowContainers.keys();
            if (keys.length > 0) {
                for (var i = 0; i < keys.length; i++) {
                    var windowContainerStruct = NPCCILY.windowContainers.get(keys[i]);
                    // $('#'+ keys[i]).css("border", "1px solid grey");
                    // $('#'+ keys[i]).addClass("videoWnd_border").removeClass("videoWnd_selected");
                    if (windowContainerStruct && windowContainerStruct.active) {
                        WebPreview.StopVideoByWindowObj(windowContainerStruct,null,function(res){
                          arr.push(res.substring(0,res.length-3))
                        });
                    }
                }

                // $('#video11').addClass("videoWnd_selected").removeClass("videoWnd_border");
            }

          var ipVal = logindata.ip;
          var portVal = logindata.port;
            WebClient.RemoveCCEvent();
            if (WebClient.chatStatusHasLogin == true) {
                // 若即时会话服务连接，则断开
                WebPreview.chatLogout();
            }

            var operator = NPCCIF.RSTW_LogoutNoBlock(NPCCILY.Plug.ccPlugin, WebClient.hServer, ipVal, portVal);
            if (operator.errorCode == ErrorCode.NP_E_OK) {
                console.log('退出登录成功');
                callback({code:"delete",arr:arr})
                windowContainerStruct.window = null;
                WebClient.connectId = null;
                WebClient.hServer = null;
                // $('#resourceTree').html('');
                // $('#login').html('登录');
                // $('#location_info').html('');

                // $(".audio").attr("disabled", true);
                // $(".talk").attr("disabled", true);
                // $(".location").attr("disabled", true);
                // $(".top").attr("disabled", true);
                // $(".bottom").attr("disabled", true);
                // $(".left").attr("disabled", true);
                // $(".right").attr("disabled", true);
                // $(".snapShot").attr("disabled", true);
                // $(".record").attr("disabled", true);

                // $('#def').val('');
                // $(".definition").attr("disabled", true);
                // $('#vol').val('');
                // $(".volume").attr("disabled", true);
                // $('#dateInfoVideoTree').html('');
                // $('#dateInfoPhotoTree').html('');
                // $('.dateInfoVideoTb tbody').html('');
                // $('.dateInfoPhotoTb tbody').html('');
                // $('#msg').html('');
                // $('#sendUserName').val('');
                // $('#content').val('');
            }
            else {
                alert('退出平台失败: ' + ErrorCode.Error2Desc(operator.errorCode));
            }
        }
        catch (e) {
            // alert('Logout exception: ' + e.name + '::' + e.message);
        }
    },

    // 添加CC插件事件
    AddCCEvent: function () {
        // 添加接收平台（设备）通知
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.event_notify,
            function (notify) {
                WebClient.ReceiveCCEvent(notify);
            }
        );

        // 添加接收流状态通知，比如开启视频流、音频流
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.stream_status_notify,
            function (notify) {
                WebClient.ReceiveStreamStatus(notify);
            }
        );

        // 接收对讲和喊话流状态通知
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.call_stream_status_notify,
            function (notify) {
                WebClient.ReceiveStreamStatus(notify);
            }
        );

        // 接收本地录像时自动切换文件的通知
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.update_record_notify,
            function (hMedia, utcTime, oldFilePath, newFIlePath) {
                WebClient.ReceiveUpdateRecord(hMedia, utcTime, oldFilePath, newFIlePath);
            }
        );

        // 接收定位数据通知
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.location_data_notify,
            function (notify) {
                WebClient.ReceiveLocationData(notify);
            }
        );

        // 接收即时会话通知
        NPCCILY.CCNotifyManager.Add(
            NPCCEnum.CCObjectNotify.chat_msg_notify,
            function (hServer, errorCode, chatMsgStatus, chatMsgContent) {
                WebClient.ReceiveChatMsg(hServer, errorCode, chatMsgStatus, chatMsgContent);
            }
        );
    },

    // 移除事件
    RemoveCCEvent: function () {
        NPCCILY.CCNotifyManager.Remove(NPCCEnum.CCObjectNotify.event_notify);
        NPCCILY.CCNotifyManager.Remove(NPCCEnum.CCObjectNotify.stream_status_notify);
        NPCCILY.CCNotifyManager.Remove(NPCCEnum.CCObjectNotify.call_stream_status_notify);
        NPCCILY.CCNotifyManager.Remove(NPCCEnum.CCObjectNotify.location_data_notify);
        NPCCILY.CCNotifyManager.Remove(NPCCEnum.CCObjectNotify.chat_msg_notify);
    },

    // 启动视频(暂未使用)
    PlayVideo: function (cameraRes) {
        try {
            if (WebPreview.CheckCameraResIsCanPlay(cameraRes)) {
                var windowContainerStruct = WebPreview.GetFreeVideoWindow();
                if (windowContainerStruct) {
                    var winObj = windowContainerStruct.window;
                    console.log(winObj)
                    if (winObj) {
                        // 开始预览视频
                        winObj.params.puid = cameraRes.puid;
                        winObj.params.resIdx = cameraRes.resIdx;
                        winObj.params.cameraResHandle = cameraRes.handle;
                        var operator = NPCCILY.StartPreview(winObj, NPCCEnum.StopRealtimePreviewType.SREP_VIDEO);
                        if (operator.errorCode == ErrorCode.NP_E_OK) {
                            operator = NPCCILY.CAM_GetDefinition(winObj);
                            if (operator.errorCode == ErrorCode.NP_E_OK) {
                                $('#def').val(operator.value);
                            }
                            else {
                                alert('获取清晰度失败：' + ErrorCode.Error2Desc(operator.errorCode));
                            }
                        }
                        else {
                          console.log(ErrorCode.Error2Desc(operator.errorCode))
                            alert('开启视频失败：' + ErrorCode.Error2Desc(operator.errorCode));
                            return false;
                        }

                        WebPreview.ClickVideoWindow(winObj);
                        windowContainerStruct.active = true;
                        return true;
                    }
                    else {
                        alert('开启视频失败，视频播放窗口还没有创建');
                        return false;
                    }
                }
                else {
                    alert('启动视频失败，没有空闲的视频窗口');
                    return false;
                }
            }
        }
        catch (e) {
            alert('启动视频异常：' + e.name + ', ' + e.message);
            return false;
        }
    },

    // 资源树控制
    ExpandsionEx: function (obj) {
        if (obj) {
            if (obj.style.display == 'none') {
                if (obj.innerHTML == '') return;
                obj.style.display = 'flex';
            }
            else {
                obj.style.display = 'none';
            }
        }
    },

    // 接收CC插件事件
    ReceiveCCEvent: function (notify) {
        var globalData = NPCCILY.serverMap.get(WebClient.connectId);
        if (globalData instanceof NPCCStruct.InitGlobalDataStruct) {
            var hServer = globalData.hServer;
            if (hServer == notify.handle) {
                if (notify.errorCode == ErrorCode.NP_E_OK) {
                    var eventID = notify.keyData.ID; // 事件ID
                    switch (Number(eventID)) {
                        case NPCCEnum.Notification.RST_EVT_SERVER_ConnectionBreak:
                            // 与平台连接断开，需要主动断开与平台之间的连接
                            alert('与平台连接断开');
                            WebClient.Logout();
                            break;
                        case NPCCEnum.Notification.RST_EVT_PU_Online:
                        // 设备上线
                        case NPCCEnum.Notification.RST_EVT_PU_Offline:
                            // 设备下线
                            var utcTime = notify.keyData.T; // 事件时间
                            var eventTime = NPCCUtils.DateFormat('yyyy-MM-dd HH:mm:ss', new Date(parseInt(utcTime) * 1000));
                            var dID = notify.keyData.DID; // 域的DID
                            var puid = notify.keyData.SID; // 设备的PUID
                            var resType = notify.keyData.RT; // 设备类型
                            var resIdx = notify.keyData.RC; // 设备索引
                            var handle = NPCCIF.RSTW_GetOnePU(NPCCILY.Plug.ccPlugin, hServer, dID , puid).value;
                            // 获取资源名称
                            var name = NPCCIF.COMMON_GetName(NPCCILY.Plug.ccPlugin, handle).value;
                            // 获取资源索引
                            resIdx = NPCCIF.COMMON_GetResIdx(NPCCILY.Plug.ccPlugin, handle).value;
                            if (Number(eventID) == NPCCEnum.Notification.RST_EVT_PU_Online) {
                                if(handle == null) {
                                }
                                else{
                                    console.log(name + '在' +eventTime+ '上线了');
                                }

                                if ($('#resourceTree').css('display') == 'block') {
                                    WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, $('#resourceTree'), NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_platform);
                                }

                                if ($('#resourceTreeFrond').css('display') == 'block') {
                                    WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, $('#resourceTreeFrond'), NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_frond);
                                }
                            }
                            else {
                                console.log(name + '在' +eventTime+ '下线了');
                                // 如果该设备视频正在播放，就停止视频后刷新列表
                                var keys = NPCCILY.windowContainers.keys();
                                if (keys.length > 0) {
                                    for (var i = 0; i < keys.length; i++) {
                                        var windowContainerStruct = NPCCILY.windowContainers.get(keys[i]);
                                        if (windowContainerStruct) {
                                            var winObj = windowContainerStruct.window;
                                            if (winObj && winObj.status.playvideoing) {
                                                // 正在预览的就是当前选中的摄像头
                                                if (winObj.params.puid == puid && winObj.params.resIdx == resIdx) {
                                                    WebPreview.StopVideoByWindowObj(windowContainerStruct);
                                                }
                                            }
                                        }
                                    }
                                }

                                if ($('#resourceTree').css('display') == 'block') {
                                    WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, $('#resourceTree'), NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_platform);
                                }

                                if ($('#resourceTreeFrond').css('display') == 'block') {
                                    WebTree.ConstructResourceTree(WebClient.hServer, WebClient.rootDomainName, $('#resourceTreeFrond'), NPCCEnum.resourceTreeTypeDemo.resourceTreeTypeDemo_frond);
                                }
                            }
                            break;
                        //侦测到火点
                        case NPCCEnum.Notification.RST_EVT_CAM_FireDetected:
                            console.log(notify);
                            // 经度
                            // var Latitude = notify.keyData.D.Longitude;
                            // 纬度
                            // var Longitude = notify.keyData.D.Latitude;
                            break;
                        // 接收到呼叫用户的响应
                        case NPCCEnum.Notification.RST_EVT_CUS_CLU_CallUserResponse:
                            console.log(notify);
                            // 0拒绝，1接听
                            if (Number(notify.keyData.D.Accept)) {
                                var puid = notify.keyData.D.PUID; // 设备的PUID
                                if (puid == WebPreview.CallUserTalkWinObj.params.puid) {
                                    var winObj = WebPreview.CallUserTalkWinObj;
                                    if (winObj.status.playaudioing) {
                                        if (!WebPreview.PlayOrStopAudio(winObj)) {
                                            winObj.params.talkbackResHandle = null;
                                            return false;
                                        }
                                    }

                                    var operator = NPCCILY.StartTalk(winObj);
                                    if (operator.errorCode == ErrorCode.NP_E_OK) {
                                        WebPreview.CallUserTalking = true;
                                        console.log('开启对讲成功');
                                        $('.callUserTalk').val('停止对讲');
                                    }
                                    else {
                                        winObj.params.talkbackResHandle = null;
                                        alert('开启对讲失败：' + ErrorCode.Error2Desc(operator.errorCode));
                                        return false;
                                    }
                                }
                            }
                            else {
                                alert('对方拒绝了你的语音通话请求');
                            }

                            break;
                        default:
                            break;
                    }
                }

            }
        }
    },

    // 接收定位数据
    ReceiveLocationData: function (notify) {
        try {
            if (notify && notify.handle) {
                NPCCILY.windowContainers.each(function (item) {
                    var windowContainerStruct = item.value;
                    var winObj = windowContainerStruct.window;
                    if (winObj && winObj.status.playvideoing) {
                        if (winObj.params.locationResHandle == notify.handle && winObj.status.playlocation) {
                            // unsigned char 状态: 0表示无模块;1表示无信号;2表示正常
                            var State = notify.keyData.State;
                            switch (Number(State)) {
                                case NPCCEnum.LocationStatus.LocationStatus_NoModule:
                                    var locationStatus = '无模块';
                                    break;
                                case NPCCEnum.LocationStatus.LocationStatus_NoSignal:
                                    var locationStatus = '无信号';
                                    break;
                                case NPCCEnum.LocationStatus.LocationStatus_HasSignal:
                                    var locationStatus = '正常';
                                    // double 纬度,取值范围[-90,90],北纬为正,南纬为负
                                    var Latitude = notify.keyData.Latitude;
                                    // double 经度,现在取值是[-180,180),东经为正,西经为负
                                    var Longitude = notify.keyData.Longitude;
                                    // float 方向,[0,360),正北为0,正东为90,依次类推
                                    var Bearing = notify.keyData.Bearing;
                                    // float 速度,单位km/h
                                    var Speed = notify.keyData.Speed;
                                    // float 海拔,单位m,小于等于-50000表示无效
                                    var Altitude = notify.keyData.Altitude;
                                    // unsigned int 时间,单位秒,UTC时间
                                    var UTCTime = notify.keyData.UTCTime;
                                    var locationTime = NPCCUtils.DateFormat('yyyy-MM-dd HH:mm:ss', new Date(parseInt(UTCTime) * 1000));

                                    var value = $('#location_info').val();
                                    if (value === '') {
                                        $('#location_info').val('时间:' + locationTime + ' 纬度: ' + Latitude + ' 经度:' + Longitude + ' 方向:' + Bearing
                                            + ' 速度:' + Speed + ' 海拔:' + Altitude);
                                    }
                                    else {
                                        $('#location_info').val(value + '\n时间:' + locationTime + ' 纬度: ' + Latitude + ' 经度:' + Longitude + ' 方向:' + Bearing
                                            + ' 速度:' + Speed + ' 海拔:' + Altitude);
                                    }

                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                });
            }
        }
        catch (e) {
            alert('ReceiveLocationData exception：' + e.message + ', ' + e.name);
        }
    },

    // 接收流状态的通知
    ReceiveStreamStatus: function (notify) {
        try {
            if (notify && notify.handle) {
                NPCCILY.windowContainers.each(
                    function (item) {
                        var windowContainerStruct = item.value;
                        var winObj = windowContainerStruct.window;
                        if (winObj && winObj.status.playvideoing) {
                            // 根据句柄匹配
                            if (winObj.params.cameraResHandle == notify.handle) {
                                if (notify.eventName == NPCCEnum.CCObjectNotify.stream_status_notify) {
                                    if (notify.errorCode == ErrorCode.NP_E_OK) {
                                        if (typeof notify.statusDesc != 'undefined' && notify.statusDesc != '') {
                                            alert('视频播放状态：' + notify.statusDesc);
                                        }
                                    }
                                    else {
                                        alert('视频播放错误：' + ErrorCode.Error2Desc(notify.errorCode));
                                    }
                                }
                            }
                            else if (winObj.params.audioResHandle == notify.handle) {
                                if (notify.eventName == NPCCEnum.CCObjectNotify.stream_status_notify) {
                                    if (notify.errorCode == ErrorCode.NP_E_OK) {
                                        if (typeof notify.statusDesc != 'undefined' && notify.statusDesc != '') {
                                            alert('音频播放状态：' + notify.statusDesc);
                                        }
                                    }
                                    else {
                                        alert('音频播放错误：' + ErrorCode.Error2Desc(notify.errorCode));
                                    }
                                }
                            }
                            else if (winObj.params.talkbackResHandle == notify.handle) {
                                if (notify.eventName == NPCCEnum.CCObjectNotify.call_stream_status_notify) {
                                    if (notify.errorCode == ErrorCode.NP_E_OK) {
                                        if (notify.keyData.type == 1) {
                                            alert('喊话成功');
                                        }
                                        else if (notify.keyData.type == 2) {
                                            alert('对讲成功');
                                        }
                                    }
                                    else {
                                        if (notify.keyData.type == 1) {
                                            alert('喊话错误：' + ErrorCode.Error2Desc(notify.errorCode));
                                        }
                                        else if (notify.keyData.type == 2) {
                                            alert('对讲错误：' + ErrorCode.Error2Desc(notify.errorCode));
                                        }
                                    }
                                }
                            }
                        }
                    }
                );
            }
        }
        catch (e) {
            alert('ReceiveStreamStatus exception：' + e.message + ', ' + e.name);
        }
    },

    // 接收录像状态通知
    ReceiveUpdateRecord: function(hMedia, utcTime, oldFilePath, newFIlePath) {
        try {
            if (hMedia) {
                NPCCILY.windowContainers.each(
                    function (item) {
                        var windowContainerStruct = item.value;
                        var winObj = windowContainerStruct.window;
                        if (winObj && winObj.status.playvideoing) {
                            if (winObj.params.mediaHandle == hMedia && winObj.status.playrecording) {
                                alert('录像自动切换文件，新文件路径为：' + newFIlePath);
                            }
                        }
                    }
                );
            }
        }
        catch (e) {
            alert('ReceiveUpdateRecord exception：' + e.message + ', ' + e.name);
        }
    },

    // 接收即时会话通知
    ReceiveChatMsg: function(hServer, errorCode, chatMsgStatus, chatMsgContent) {
        try {
            if (hServer == WebClient.hServer && errorCode == ErrorCode.NP_E_OK) {
                if (chatMsgStatus == NPCCEnum.ChatMsgStatus.ChatMsg_Status_Login) {
                    console.log('表示即时会话服务已连接');
                    WebClient.chatStatusHasLogin = true;
                }
                else if (chatMsgStatus == NPCCEnum.ChatMsgStatus.ChatMsg_Status_Logout) {
                    console.log('表示即时会话服务断开');
                    WebClient.chatStatusHasLogin = false;
                }
                else if (chatMsgStatus == NPCCEnum.ChatMsgStatus.ChatMsg_Status_SendComplete) {
                    console.log('表示发送一次消息完成');
                    var resChatMsgContent = JSON.parse(chatMsgContent);
                    var userName = $('#userName').val();
                    var charContent = '<span>'+ userName + ' ('+WebPreview.CalcUTCTime()+') ' + '</span>' + '<br/>' +
                        NPCCUtils.UTF8toUnicode(resChatMsgContent.Message) + '<br/>';
                    var p = $('<p>');
                    p.html(charContent);
                    $("#msg").append(p);

                }
                else if (chatMsgStatus == NPCCEnum.ChatMsgStatus.ChatMsg_Status_ReceiveComplete) {
                    console.log('接收一次消息完成');
                    // 如果登录的用户与发送的用户相同，则不用显示信息
                    if ($('#userName').val() == $('#sendUserName').val()) {
                        return;
                    }
                    var resChatMsgContent = JSON.parse(chatMsgContent);
                    var charContent = '<span>'+ resChatMsgContent.User + ' ('+WebPreview.CalcUTCTime(resChatMsgContent.Time * 1000)+') ' +
                        '</span>' + '<br/>' + NPCCUtils.UTF8toUnicode(resChatMsgContent.Message) + '<br/>';
                    var p = $('<p>');
                    p.html(charContent);
                    $("#msg").append(p);
                }
            }
        }
        catch (e) {
            alert('ReceiveChatMsg exception：' + e.message + ', ' + e.name);
        }
    },

    // 接受PW插件事件
    ReceivePWEvent: function (notify) {
        if (notify.eventName == "lbtn_click") {
            WebPreview.ClickVideoWindow(notify.handle);
        }
        else if (notify.eventName == "full_screen_window_show") {
            WebPreview.ShowFullWindow(notify);
        }
        else if (notify.eventName == "full_screen_window_hide") {
            WebPreview.HideFullWindow(notify);
        }
    },

    // 用户管理接口(测试)
    UserManageTest: function() {
        // 获取用户ID
        var operator = NPCCILY.GetUID(WebClient.connectId);
        if (operator.errorCode == ErrorCode.NP_E_OK) {
            var userIndex = operator.value;
            // 添加子用户
            operator = NPCCILY.AddUser(WebClient.connectId, userIndex, NPCCUtils.encodeUnicode(NPCCUtils.UnicodetoUTF8("maoTest")),
                'rji123', NPCCEnum.UserType.UserType_Group, NPCCUtils.encodeUnicode(NPCCUtils.UnicodetoUTF8("软件工程师")),
                NPCCEnum.PUFeature.PUFeature_GroupFunction|NPCCEnum.PUFeature.PUFeature_InstantMessage|
                NPCCEnum.PUFeature.PUFeature_ExtenelCamera|NPCCEnum.PUFeature.PUFeature_WirelessCamera|NPCCEnum.PUFeature.PUFeature_LocalFaceRecognition);
            if (operator.errorCode == ErrorCode.NP_E_OK) {
                alert('添加用户成功');
                var subUserIndex = operator.value;
                // 给新加的用户分配资源。
                var addUserResList = [];
                // 开始获取设备列表
                var puResList = NPCCILY.ForkPUList(WebClient.connectId).value;
                if (puResList) {
                    for (var i=0; i<puResList.length; i+=2) {
                        if (puResList[i].resType == NPCCEnum.ResType.RES_TYPE_DEV)
                        {
                            addUserResList.push(puResList[i].resID);
                        }
                    }
                }

                operator = NPCCILY.AddUserRes(WebClient.connectId, subUserIndex, addUserResList);
                if (operator.errorCode == ErrorCode.NP_E_OK) {
                    alert('添加用户资源成功');
                } else {
                    alert('添加用户资源失败'  + ErrorCode.Error2Desc(operator.errorCode));
                }

                // 删除用户绑定的资源，一般是当前用户删除子用户的资源
                // operator = NPCCILY.RemoveUserRes(WebClient.connectId, userIndex, deleteUserResList);
                // if (operator.errorCode == ErrorCode.NP_E_OK) {
                //     alert('删除用户资源成功');
                // } else {
                //     alert('删除用户资源失败');
                // }
            }
            else {
                alert('添加用户失败：' + ErrorCode.Error2Desc(operator.errorCode));
            }

            // 获取子用户信息
            operator = NPCCILY.GetUserList(WebClient.connectId);
            if (operator.errorCode == ErrorCode.NP_E_OK) {
                alert('获取子用户信息成功');
                var userList = operator.value;
                for (var i=0; i<userList.length; i+=2) {
                    var user = userList[i];
                }
            }
            else {
                alert('获取子用户信息失败'  + ErrorCode.Error2Desc(operator.errorCode));
            }

            // 获取当前用户绑定的资源，返回的是资源ID数组
            operator = NPCCILY.GetUserRes(WebClient.connectId, userIndex);
            if (operator.errorCode == ErrorCode.NP_E_OK) {
                alert('获取当前用户绑定的资源成功');
                var userResList = operator.value;
                var deleteUserResList = [];
                if (userResList) {
                    for (var i = 0; i < userResList.length; i += 2) {
                        deleteUserResList.push(userResList[i]);
                    }
                }
            }
            else {
                alert('获取当前用户绑定的资源失败');
            }
        }
        else {
            alert('获取用户ID失败：' + ErrorCode.Error2Desc(operator.errorCode));
        }
    },

    // 点击系统管理
    sysClick: function() {
    },

    // 点击窗口设置其是否获取焦点
    setFocus: function(key) {
        var keys = NPCCILY.windowContainers.keys();
        var windowContainerStruct;
        for (var i = 0; i < keys.length; i++) {
            windowContainerStruct = NPCCILY.windowContainers.get(keys[i]);
            windowContainerStruct.focus = false;
        }

        if (key) {
            windowContainerStruct = NPCCILY.windowContainers.get(key);
            if (windowContainerStruct) {
                windowContainerStruct.focus = true;
            }
        }

        // $(".closeView").attr("disabled", true);
        // $(".audio").attr("disabled", true);
        // $(".talk").attr("disabled", true);
        // $(".location").attr("disabled", true);
        // $(".top").attr("disabled", true);
        // $(".bottom").attr("disabled", true);
        // $(".left").attr("disabled", true);
        // $(".right").attr("disabled", true);
        // $(".snapShot").attr("disabled", true);
        // $(".record").attr("disabled", true);
        // $(".callUserTalk").attr("disabled", true);
        // $('.callUserTalk').val('语音通话');
        // $(".platformStorage").attr("disabled", true);
        // $('.platformStorage').val('手动开启平台录像');

        // $('#location_info').val('');
        // $('#def').val('');
        // $(".definition").attr("disabled", true);
        // $('#vol').val('');
        // $(".volume").attr("disabled", true);
    },

    end: true
}